package com.sinosoft.hydra.um.services;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.sinosoft.hydra.logging.LogModules;
import com.sinosoft.hydra.um.condition.SearchLogPackageCondition;
import cn.com.sinux.spring.exception.ServiceException;
import com.sinosoft.hydra.um.repositories.SysLogPackageRepository;
import cn.com.sinux.spring.utils.SpecificationHelper;
import cn.com.sinux.spring.utils.ValidatorUtils;;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import com.sinosoft.hydra.um.domain.permission.SysLogPackage;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

/**
 * 日志打包业务逻辑层interface，完成打包管理的相关操作
 * @author < a href="mailto:oujianlin@sinux.com.cn">oujianlin</a>
 * created 2014-12-4
 */
@Service
public class SysLogPackageService {


    @Autowired
    private SysLogPackageRepository sysLogPackageRepository;
    @Autowired
    private FileService fileService;

    /**
     * 查询所有打包的日志
     *
     * @param pageable
     * @param searchLogPackageCondition
     * @return
     */
    public Page<SysLogPackage> findAllByPage(Pageable pageable, SearchLogPackageCondition searchLogPackageCondition) {
        final SearchLogPackageCondition condition = searchLogPackageCondition == null
                ? new SearchLogPackageCondition()
                : searchLogPackageCondition;
        Specification<SysLogPackage> specification = SpecificationHelper.buildSpecification(new SpecificationHelper.SpecificationBuilder<SysLogPackage>() {

            public void fillParam(Root<SysLogPackage> root, CriteriaBuilder cb, List<Predicate> list) {
                if (org.apache.commons.lang.StringUtils.isNotBlank(condition.getPackageName())) {
                    list.add(cb.like(root.get("packageName").as(String.class), "%" + condition.getPackageName() + "%"));
                }
                if (condition.getStartDate() != null) {
                    list.add(cb.greaterThanOrEqualTo(root.get("createDate").as(Date.class), condition.getStartDate()));
                }
                if (condition.getEndDate() != null) {
                    list.add(cb.lessThanOrEqualTo(root.get("createDate").as(Date.class), condition.getEndDate()));
                }
                if (condition.getIsUploaded() != null) {
                    list.add(cb.equal(root.get("isUploaded").as(Integer.class), condition.getIsUploaded()));
                }
            }
        });
        return sysLogPackageRepository.findAll(specification, pageable);
    }

    /**
     * 删除打包
     *
     * @param jsonIds
     * @return
     */
    @Transactional
    public List<SysLogPackage> deleteLogPackage(List<String> jsonIds) {
        if (ValidatorUtils.isArrayEmpty(jsonIds)) {
            throw new ServiceException("删除失败，参数出错");
        }
        String relativePath = fileService.getRelativePath();
        List<SysLogPackage> logPackages = this.sysLogPackageRepository.findAll(jsonIds);
        List<String> errorFiles = new ArrayList<String>();
        for (SysLogPackage logPackage : logPackages) {
            if (StringUtils.isNotBlank(logPackage.getLogFile())) {
                String path = relativePath + logPackage.getLogFile();
                File file = new File(path);
                if (file.exists() && !file.delete()) {
                    errorFiles.add(logPackage.getPackageName() + "位置:" + path);
                }
            }
            this.sysLogPackageRepository.delete(logPackage);
        }
        if(!errorFiles.isEmpty()){
            LoggerFactory.getLogger(LogModules.OPT_LOGGER).error("删除打包日志物理文件失败，请手动给删除，路径{}", StringUtils.join(errorFiles, ","));
        }
        return logPackages;
    }
}
